<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Str;


class User extends Authenticatable
{
    use HasFactory, Notifiable;
    //通过自动添加属性加的不知道对不对
  //  public String $name='';

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'is_actived',//这里应该是is_active还是is_actived呢
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected $casts=[
        'email_verified_at'=>'datetime',
    ];



    //获取用户头像
    public function getAvatar()
    {
       return url('avatar/avatar'.($this->attributes['id']%7==0?2:$this->attributes['id']%7).'.png');
    }

    public static function boot()
    {
        parent::boot();
        static::creating(function ($user) {
             $user->active_token = Str::random(60);
        });
    }

    //对文章的模型关联 一对多
    public function posts()
    {
        return $this->hasMany(Post::class);
    }

    public function userHasPosts()
    {
        $user_ids = $this->fanings->pluck('id')->toArray();
        array_push($user_ids,$this->id);
        return Post::whereIn('user_id',$user_ids)->with('user')->orderBy('created_at','DESC');
    }

    //某人的粉丝
    public function fans(){
        return $this->belongsToMany(User::class,'fans','user_id','fan_id');
    }
    //某人关注了哪些人
    public function fanings(){
        return $this->belongsToMany(User::class,'fans','fan_id','user_id');
    }
    //关注某人
    public function fan($user_id)
    {
       if (!is_array($user_id)){
           $user_id = compact('user_id');
       }
       $this->fanings()->sync($user_id,false);
    }
    //取消关注
    public function unfan($user_id)
    {
        if (!is_array($user_id)){
            $user_id = compact('user_id');
        }
        $this->fanings()->detach($user_id,false);
    }
    //判断某人是否关注了某人
    public function isFaning($user_id)
    {
       return $this->fanings->contains($user_id);
    }
}
